package com.bdth.interceptor;

import com.bdth.controller.BaseController;
import com.bdth.model.User;
import com.bdth.utils.HtmlUtil;
import com.bdth.utils.SessionUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录认证的拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

	/**
	 * Handler执行完成之后调用这个方法
	 */
	public void afterCompletion(HttpServletRequest request,
	                            HttpServletResponse response, Object handler, Exception exc)
			throws Exception {

	}

	/**
	 * Handler执行之后，ModelAndView返回之前调用这个方法
	 */
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
	                       Object handler, ModelAndView modelAndView) throws Exception {
	}

	/**
	 * Handler执行之前调用这个方法
	 */
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
	                         Object handler) throws Exception {
		//获取请求的URL
		String url = request.getRequestURI();
		//URL:login.jsp是公开的;这个demo是除了login.jsp是可以公开访问的，其它的URL都进行拦截控制
		if (url.indexOf("login") >= 0) {
			return true;
		}
		if (url.indexOf("toLogin") >= 0) {
			return true;
		}
		//获取Session
		User user = SessionUtils.getUser(request);

		if (user != null) {
			return true;
		}
		//不符合条件的，跳转到登录界面
		String path = request.getContextPath();

		//如果request.getHeader("X-Requested-With") 返回的是"XMLHttpRequest"说明就是ajax请求，需要特殊处理 否则直接重定向就可以了
		if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) { //如果是ajax请求响应头会有x-requested-with
			Map<String, Object> result = new HashMap<String, Object>();
			result.put(BaseController.SUCCESS, false);
			result.put(BaseController.LOGOUT_FLAG, true);//登录标记 true 退出
			result.put(BaseController.MSG, "登录超时.");
			HtmlUtil.writerJson(response, result);

		} else {
			response.sendRedirect(path + "/login");
		}

		return false;
	}

}